package com.zmc.product.controller;

import com.zmc.common.enums.CommonCodeEnum;
import com.zmc.common.utils.R;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.product.infrastructure.entity.CommodityCategoryEntity;
import com.zmc.product.infrastructure.bean.query.CommodityCategoryQuery;
import com.zmc.product.infrastructure.service.CommodityCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 商品中心的类目Controller
 *
 * @author zmc
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CommodityCategoryService commodityCategoryService;

    @Autowired
    private AuthTokenService authTokenService;

    /**
     * 查询商品中心的类目列表
     */
    @PostMapping("/list")
    public R list(@RequestBody CommodityCategoryQuery query) {
        List<CommodityCategoryEntity> list = commodityCategoryService.selectCommodityCategoryList(query);
        return R.ok(list);
    }

    /**
     * 获取商品中心的类目详细信息
     */
    @PostMapping(value = "/info")
    public R getInfo(@RequestBody CommodityCategoryEntity commodityCategory) {
        return R.ok(commodityCategoryService.getById(commodityCategory.getId()));
    }

    /**
     * 新增商品中心的类目
     */
    @PostMapping("/add")
    public R add(@RequestBody CommodityCategoryEntity commodityCategory) {
        CommodityCategoryEntity parent = commodityCategoryService.getById(commodityCategory.getParentId());
        if (parent.getLevel() == 3) {
            return R.error("最多只支持三级节点");
        }
        commodityCategory.setLevel(parent.getLevel() + 1);
        commodityCategory.setIsLeaf(CommonCodeEnum.CATEGORY_IS_LEAF.getCode());
        String username = authTokenService.getUserInfo().getUsername();
        commodityCategory.setCreateBy(username);
        commodityCategoryService.save(commodityCategory);
        return R.ok();
    }

    /**
     * 修改商品中心的类目
     */
    @PostMapping("/update")
    public R edit(@RequestBody CommodityCategoryEntity commodityCategory) {
        String username = authTokenService.getUserInfo().getUsername();
        commodityCategory.setUpdateBy(username);
        commodityCategoryService.updateById(commodityCategory);
        return R.ok();
    }


    /**
     * 删除商品中心的类目
     */
    @PostMapping("/delete")
    public R remove(@RequestBody CommodityCategoryEntity commodityCategory) {
        commodityCategoryService.removeById(commodityCategory.getId());
        return R.ok();
    }
}
